// pages/addressManage/addressManage.js
const app = getApp();
import api from '../../api/index.js';
const { request } = require('../../utils/wx-api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasAddress:false,
    addressList:''
  },
  createAddress(){
    wx.navigateTo({
      url: '../createAddress/createAddress'
    })
  },
  editAddress(e){  //编辑地址
    // console.log(e);
    let {id} = e.currentTarget.dataset;
    if (e.target.dataset.del){  //删除地址
      let {index} = e.target.dataset;
      let {addressList} = this.data;
      request({ url: api.addressDel }, { id }, 'POST', { 'X-Nideshop-Token': app.globalData.token })
      .then(res => {
        addressList.splice(index, 1);
        this.setData({
          addressList
        })
        if(addressList.length==0){
          this.setData({
            hasAddress: false
          })
        }
        // console.log('del', res);
      })
    }else {
      wx.navigateTo({
        url: `../createAddress/createAddress?id=${id}`
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(app);
    request({url:api.addressList},{},'GET',{'X-Nideshop-Token':app.globalData.token})
    .then(res=>{
      console.log('list',res);
      let addressList = res.data.data;
      if (addressList.length==0){
        this.setData({
          hasAddress:false
        })
      }else {
        this.setData({
          addressList,
          hasAddress: true
        })
        addressList.forEach(ele=>{
          if (ele.is_default) {
            wx.setStorageSync('addressId',ele.id);
            app.globalData.addressId = wx.getStorageSync('addressId');
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})